package com.example.ossdemo.util;

import com.aliyun.oss.HttpMethod;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.*;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.auth.sts.AssumeRoleRequest;
import com.aliyuncs.auth.sts.AssumeRoleResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.example.ossdemo.MD5Utils;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.net.URL;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

public class OSSUtil2 {
    @Autowired
    static MD5Utils md5Utils;
    // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
    static String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
    // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
    static String accessKeyId = "LTAI5t8Bysc6H7fUCiXWVBHL";
    static String accessKeySecret = "H1xr8O6a3iorB963Yqn2Naozo29eKO";
    // 填写Bucket名称。
    static String bucketName = "soec1";
    // 填写Object的完整路径。Object完整路径中不能包含Bucket名称。
    static String objectName = "soec/6.png";


    public  static   String   upload(){
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

//        File file=new File("d:\\3.png");
//
//        ossClient.putObject(bucketName, objectName, file);
//        String url ="https://"+bucketName+"."+endpoint.substring(8)+"/"+objectName;
        String location = ossClient.getBucketLocation(bucketName);
//        System.out.println("location = " + location);
//        关闭连接
        ossClient.shutdown();

        return location;
//        return url;
    }
    public  static   void    info(){
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

//        File file=new File("d:\\3.png");
//
//        ossClient.putObject(bucketName, objectName, file);
//        String url ="https://"+bucketName+"."+endpoint.substring(8)+"/"+objectName;
        // 存储空间的信息包括地域（Region或Location）、创建日期（CreationDate）、拥有者（Owner）等。
// 填写Bucket名称，例如examplebucket。
        BucketInfo info = ossClient.getBucketInfo("soec");
// 获取地域。
        System.out.println(info.getBucket().getLocation());
// 获取创建日期。
        System.out.println("infoCreationDate = " + info.getBucket().getCreationDate());
// 获取拥有者信息。
        System.out.println("infoOwner = " + info.getBucket().getOwner());
// 获取容灾类型。
        System.out.println("infoDataRedundancyType = " + info.getDataRedundancyType());
//        System.out.println("location = " + location);
//        关闭连接
        ossClient.shutdown();

//        return url;
    }

    public  static   void    readWriteMenu(){
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

//        File file=new File("d:\\3.png");
//
//        ossClient.putObject(bucketName, objectName, file);
//        String url ="https://"+bucketName+"."+endpoint.substring(8)+"/"+objectName;
        // 存储空间的信息包括地域（Region或Location）、创建日期（CreationDate）、拥有者（Owner）等。
        ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
        AccessControlList acl = ossClient.getBucketAcl(bucketName);
        System.out.println(acl.toString());
        CreateBucketRequest soec2 = new CreateBucketRequest("soec2");
        ossClient.createBucket(soec2);
//        VoidResult voidResult = ossClient.deleteBucket("soec2");
//        System.out.println("voidResult成功 = " + voidResult);
//        System.out.println("location = " + location);
//        关闭连接
        ossClient.shutdown();

//        return url;
    }

    public  static   void    biaoqian(){
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

//        File file=new File("d:\\3.png");
//
//        ossClient.putObject(bucketName, objectName, file);
//        String url ="https://"+bucketName+"."+endpoint.substring(8)+"/"+objectName;
        // 给bucket设置标签
        SetBucketTaggingRequest request = new SetBucketTaggingRequest(bucketName);
        // 依次填写Bucket标签的键（例如owner）和值（例如hang）。可以设置多个标签但不超过20个
        request.setTag("owner", "hang");
        request.setTag("location", "hangzhou");
        ossClient.setBucketTagging(request);
        TagSet tagSet = ossClient.getBucketTagging(bucketName);
        Map<String, String> allTags = tagSet.getAllTags();
        for (Map.Entry tag : allTags.entrySet()) {
            System.out.println("tag = " + tag);
        }

        ListBucketsRequest listBucketsRequest = new ListBucketsRequest();
        listBucketsRequest.setTag("owner","hang");
        BucketList list = ossClient.listBuckets(listBucketsRequest);
        for (Bucket bucket : list.getBucketList()) {
            System.out.println("bucket = " + bucket.getName());
        }
        ossClient.deleteBucketTagging(bucketName);
//        VoidResult voidResult = ossClient.deleteBucket("soec2");
//        System.out.println("voidResult成功 = " + voidResult);
//        System.out.println("location = " + location);
//        关闭连接
        ossClient.shutdown();

//        return url;
    }


    public  static   void    StsServiceSample() throws ClientException {
        String endpoint = "sts.cn-hangzhou.aliyuncs.com";
        // 填写步骤1生成的访问密钥AccessKey ID和AccessKey Secret。
        // 填写步骤3获取的角色ARN。
        String  assessKeyId="LTAI5tAnPtQqzijKptqoPcNj";
        String  accessKeySecret="NsVxz8D8CaGmgWUw7l7AiJLeZeYUCt";
        String  roleArn = "acs:ram::1594853962978646:role/ramosstest";
        // 自定义角色会话名称，用来区分不同的令牌，例如可填写为SessionTest。
        String roleSessionName = "sessionTest";
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, assessKeyId, accessKeySecret);
        String policy = "{\n" +
                "    \"Version\": \"1\", \n" +
                "    \"Statement\": [\n" +
                "        {\n" +
                "            \"Action\": [\n" +
                "                \"oss:PutObject\"\n" +
                "            ], \n" +
                "            \"Resource\": [\n" +
                "                \"acs:oss:*:*:soec/*\" \n" +
                "            ], \n" +
                "            \"Effect\": \"Allow\"\n" +
                "        }\n" +
                "    ]\n" +
                "}";
        // regionId表示RAM的地域ID。以华东1（杭州）地域为例，regionID填写为cn-hangzhou。也可以保留默认值，默认值为空字符串（""）。
        String regionId = "cn-hangzhou";
        // 添加endpoint。适用于Java SDK 3.12.0及以上版本。
        DefaultProfile.addEndpoint(regionId, "Sts", endpoint);
        // 添加endpoint。适用于Java SDK 3.12.0以下版本。
        // DefaultProfile.addEndpoint("",regionId, "Sts", endpoint);
        // 构造default profile。
        IClientProfile profile = DefaultProfile.getProfile(regionId, assessKeyId, accessKeySecret);
        // 构造client。
        DefaultAcsClient client = new DefaultAcsClient(profile);
        final AssumeRoleRequest request = new AssumeRoleRequest();
        // 适用于Java SDK 3.12.0及以上版本。
        request.setSysMethod(MethodType.POST);
        // 适用于Java SDK 3.12.0以下版本。
        //request.setMethod(MethodType.POST);
        request.setRoleArn(roleArn);
        request.setRoleSessionName(roleSessionName);
        request.setPolicy(policy); // 如果policy为空，则用户将获得该角色下所有权限。
        request.setDurationSeconds(1200L); // 设置临时访问凭证的有效时间为3600秒。
        final AssumeRoleResponse response = client.getAcsResponse(request);
        System.out.println("Expiration: " + response.getCredentials().getExpiration());
        System.out.println("Access Key Id: " + response.getCredentials().getAccessKeyId());
        System.out.println("Access Key Secret: " + response.getCredentials().getAccessKeySecret());
        System.out.println("Security Token: " + response.getCredentials().getSecurityToken());
        System.out.println("RequestId: " + response.getRequestId());

        ossClient.shutdown();

//        return url;
    }
    public  static   void    send() throws Exception {
// Endpoint以杭州为例，其它Region请按实际情况填写。
        String endpoint = "oss-cn-shanghai.aliyuncs.com";
// 填写步骤五获取的临时访问密钥（AccessKey ID和AccessKey Secret）。
        String  assessKeyId="STS.NSnVVPT5R2vaF2gzxHbpxAvLU";
        String  accessKeySecret="oKtV6TLb9upuGYmqNYVcuzBDme4d5NZXDmJVa8PG4TY";
// 填写步骤五获取的安全令牌SecurityToken。
        String securityToken = "CAISkQJ1q6Ft5B2yfSjIr5DbHezkuepzhbSKRBTWnngdbv9UrrPntzz2IH9MenRsBOEZtPU2mGBQ6/gSlqJoRoReREvCUcZr8syzK+NUp9KT1fau5Jko1beqewHKeRSZsebWZ+LmNpy/Ht6md1HDkAJq3LL+bk/Mdle5MJqP+/kFC9MMRVuAcCZhDtVbLRcY8K18D3bKMuu3ORPHm3fZCFES2jBxkmRi86+ysLH+kBPVlw/90fRH5dazcIOjYsIrfrUHCorkgLwrLfufin8Pu0YWqp0b1vIUpW312fiGGERU7hm8NO7Zz8ZiNgcRZNJhRPYa8aShxKIi67WPx9yqlUZXX/tcViPEX5yt29fUpiF7oROB99wagAGrXORTFywZ74yc9xGh5AHZu5FQPO6F+0ykfo1yi+lXryrzyocLyu/KdzXbO+VMY5yyStMXqGiIADHlm/o2chIvcfdWS7ZusbyztbG/UdQYZzI9bs7AEdCJxbz13XzBl2PGbRKfCn57k7tP+f17r2nkcCwHHA1uV/+k5Sm6cXTXJw==";

// 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, assessKeyId, accessKeySecret, securityToken);
        Date expiration = new Date(new Date().getTime() + 1200 * 1000 ) ;
        GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, objectName, HttpMethod.PUT);
        //设置过期时间
        request.setExpiration(expiration);
        // 设置ContentType。
        request.setContentType("application/txt");
        // 通过HTTP PUT请求生成签名URL。
        URL signedUrl = ossClient.generatePresignedUrl(request);
        MD5Utils md5Utils1 =new MD5Utils();

        File f = new File("d://1.txt");
        FileInputStream fin = null;
        fin = new FileInputStream(f);
//        String s = signedUrl.toString();
//        String[] split = s.split(":");
//        String[] split1 = split[1].split("/?");

        System.out.println("signedUrl = " + signedUrl);
// 将本地文件exampletest.txt上传至目标存储空间examplebucket下的目录exampledir。
        PutObjectRequest putObjectRequest = new PutObjectRequest("soec", "exampledir/exampletest.txt", new File("D:\\1.txt"));

// 如果需要上传时设置存储类型与访问权限，请参考以下示例代码。
// ObjectMetadata metadata = new ObjectMetadata();
// metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
// metadata.setObjectAcl(CannedAccessControlList.Private);
// putObjectRequest.setMetadata(metadata);

// 上传文件。
//        ossClient.putObject(putObjectRequest);

// 关闭OSSClient。
        ossClient.shutdown();
    }

    public  static   void    AssumeRole() throws Exception {
        //构建一个阿里云客户端，用于发起请求。
        //设置调用者（RAM用户或RAM角色）的AccessKey ID和AccessKey Secret。
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAI5tQM3AfCvvG14bT6Tx63", "LbuYDdTtU3YtnebGQzUyjanQFIjM2w");
        IAcsClient client = new DefaultAcsClient(profile);

        //构造请求，设置参数。
        AssumeRoleRequest request = new AssumeRoleRequest();
        request.setRegionId("cn-hangzhou");
        request.setRoleArn("acs:ram::1594853962978646:role/aliyunosstokengeneratorrole");
        request.setRoleSessionName("external-username");

        AssumeRoleResponse response = client.getAcsResponse(request);
        System.out.println(1);
        String s = new Gson().toJson(response);
        System.out.println(s);


// 创建OSSClient实例。
//        OSS ossClient = new OSSClientBuilder().build(endpoint, assessKeyId, accessKeySecret, securityToken);
//        Date expiration = new Date(new Date().getTime() + 3600 * 1000);
//        GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, objectName, HttpMethod.PUT);
//        //设置过期时间
//        request.setExpiration(expiration);
//        // 设置ContentType。
//        request.setContentType("application/txt");
//        // 通过HTTP PUT请求生成签名URL。
//        URL signedUrl = ossClient.generatePresignedUrl(request);

//        File f = new File("d://1.txt");
//        FileInputStream fin = null;
//        fin = new FileInputStream(f);
//        System.out.println("signedUrl = " + signedUrl);
// 将本地文件exampletest.txt上传至目标存储空间examplebucket下的目录exampledir。
//        PutObjectRequest putObjectRequest = new PutObjectRequest("soec", "exampledir/exampletest.txt", new File("D:\\1.txt"));

// 如果需要上传时设置存储类型与访问权限，请参考以下示例代码。
// ObjectMetadata metadata = new ObjectMetadata();
// metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
// metadata.setObjectAcl(CannedAccessControlList.Private);
// putObjectRequest.setMetadata(metadata);

// 上传文件。
//        ossClient.putObject(putObjectRequest);

// 关闭OSSClient。
//        ossClient.shutdown();
    }


    public  static   void    yuan() throws Exception {
// Endpoint以杭州为例，其它Region请按实际情况填写。
//        String endpoint = "oss-cn-shanghai.aliyuncs.com";
//// 填写步骤五获取的临时访问密钥（AccessKey ID和AccessKey Secret）。
//        String  assessKeyId="STS.NSnVVPT5R2vaF2gzxHbpxAvLU";
//        String  accessKeySecret="oKtV6TLb9upuGYmqNYVcuzBDme4d5NZXDmJVa8PG4TY";
//// 填写步骤五获取的安全令牌SecurityToken。
//        String securityToken = "CAISkQJ1q6Ft5B2yfSjIr5DbHezkuepzhbSKRBTWnngdbv9UrrPntzz2IH9MenRsBOEZtPU2mGBQ6/gSlqJoRoReREvCUcZr8syzK+NUp9KT1fau5Jko1beqewHKeRSZsebWZ+LmNpy/Ht6md1HDkAJq3LL+bk/Mdle5MJqP+/kFC9MMRVuAcCZhDtVbLRcY8K18D3bKMuu3ORPHm3fZCFES2jBxkmRi86+ysLH+kBPVlw/90fRH5dazcIOjYsIrfrUHCorkgLwrLfufin8Pu0YWqp0b1vIUpW312fiGGERU7hm8NO7Zz8ZiNgcRZNJhRPYa8aShxKIi67WPx9yqlUZXX/tcViPEX5yt29fUpiF7oROB99wagAGrXORTFywZ74yc9xGh5AHZu5FQPO6F+0ykfo1yi+lXryrzyocLyu/KdzXbO+VMY5yyStMXqGiIADHlm/o2chIvcfdWS7ZusbyztbG/UdQYZzI9bs7AEdCJxbz13XzBl2PGbRKfCn57k7tP+f17r2nkcCwHHA1uV/+k5Sm6cXTXJw==";

// 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        SimplifiedObjectMeta objectMeta = ossClient.getSimplifiedObjectMeta(bucketName, objectName);
        System.out.println(objectMeta.getSize());
        System.out.println(objectMeta.getETag());
        System.out.println(objectMeta.getLastModified());

        // 获取文件的全部元信息。
        ObjectMetadata metadata = ossClient.getObjectMetadata(bucketName, objectName);
        System.out.println(metadata.getContentType());
        System.out.println(metadata.getLastModified());
        System.out.println(metadata.getExpirationTime());
// 如果需要上传时设置存储类型与访问权限，请参考以下示例代码。
// ObjectMetadata metadata = new ObjectMetadata();
// metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
// metadata.setObjectAcl(CannedAccessControlList.Private);
// putObjectRequest.setMetadata(metadata);

// 上传文件。
//        ossClient.putObject(putObjectRequest);

// 关闭OSSClient。
        ossClient.shutdown();
    }



    public static void main(String[] args) throws Exception {
//        System.out.println(upload());
//        info();
//        readWriteMenu();
//        biaoqian();
//        StsServiceSample();
//        send();
//        AssumeRole();
        yuan();
    }
}
